/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Actor.weapons;

import Actor.Actor;
import actor.weapons.Rocket;
import javax.vecmath.Point2d;

/**
 *
 * @author Eric-Standard
 */
public class TargetedMissile extends Rocket {

    private Actor target = null;
    private Point2d targetPoint = null;
    private static final int DEFAULT_ACCEL = 1000;
    private double acc = DEFAULT_ACCEL;
    private static final int DEFAULT_SPEED = 400;
    protected double prevDist = Double.POSITIVE_INFINITY;

    public Actor getTarget() {
        return target;
    }

    public void setTarget(Actor target) {
        this.target = target;
    }

    public void setTargetPoint(Point2d target) {
        this.targetPoint = target;
    }

    public TargetedMissile(Actor owner) {
        super(owner);
    }

    public TargetedMissile(Actor owner, Actor target) {
        super(owner);
        this.target = target;
        this.fuseTime = (long) 1e10;
    }

    public TargetedMissile(Actor owner, Point2d target) {
        super(owner);
        this.targetPoint = target;
    }

    @Override
    public void act(long dt) {
        super.act(dt);
        if (target != null && target.isActive) {
            Point2d posT = target.getPos();
            double angleT = Math.atan2(posT.y - pos.y, posT.x - pos.x);
            angle = Math.atan2(vel.y, vel.x);
            double angleToTurn = 0;
            double wrapAngle = (angleT - angle);
            while (wrapAngle >= Math.PI) {
                wrapAngle -= 2 * Math.PI;
            }
            while (wrapAngle < -Math.PI) {
                wrapAngle += 2 * Math.PI;
            }
            double dist = pos.distance(posT);
            if (dist > prevDist) {
                System.out.println(angleT * 180 / Math.PI);
                angleToTurn = angleT;
            } else if (Math.abs(angleT - angle) < 1e-8) {
                angleToTurn = angle;
            } else if (wrapAngle < 0) {
                //Left turn
                angleToTurn = (angle - Math.PI / 2);
            } else {
                //Right turn
                angleToTurn = (Math.PI / 2 + (angle));
            }
            prevDist = dist;
            vel.x += dt / 1000f * acc * Math.cos(angleToTurn);
            vel.y += dt / 1000f * acc * Math.sin(angleToTurn);
            vel.normalize();
            vel.scale(DEFAULT_SPEED);
        }
    }
}